<!--
  @author:  long
  @date:    2023/3/28
  @file:    xx
  @require:
-->
<template>
  <div>
    <el-input v-model="filterText" placeholder="请输入关键字" class="mb-15px" />
    <el-tree
      ref="treeRef"
      :data="treeOption.data"
      :node-key="treeOption.nodeKey"
      show-checkbox
      :default-expanded-keys="treeOption.defaultExpandedKeys"
      :check-strictly="treeOption.checkStrictly"
      :class="treeOption.multiple ? '' : 'customNodeClass'"
      :check-on-click-node="true"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      @check="nodeClick"
      :default-checked-keys="treeOption.defaultCheckedKeys"
      :props="treeProps"
    />
  </div>
</template>

<script setup name="CustomTree">
import { getCurrentInstance, nextTick } from 'vue'
import { ElTree } from 'element-plus'
import useCommonStore from '@/store/modules/common'
import { handleTree } from '@/utils/ruoyi'
import { getListWithRole } from '@/api/system/dept'
import { treeselect } from '@/api/rsgl/zzjg'
const props = defineProps({
  componentOptions: {
    type: Object,
    required: true,
    default: () => {
      return { nodekey: 'id' }
    }
  }
})
const { proxy } = getCurrentInstance()
// 通用数据store
const commonStore = useCommonStore()
const treeRef = ref(null)
// 选中的数据
const selectData = ref([])
const treeOption = ref({})
const treeProps = ref({ label: 'label', children: 'children' })
const emit = defineEmits(['ok'])

// rsgl_ygda_position 职务
const { rsgl_ygda_position } = proxy.useDict('rsgl_ygda_position')

watchEffect(
  () => {
    //获取tree数据
    getTreeData()
  },
  { flush: 'post' }
)

const init = () => {
  // 获取tree配置
  treeOption.value = JSON.parse(JSON.stringify(props.componentOptions))

  // 获取treeProps配置
  treeProps.value.label = treeOption.value.treeLabelName
}

init()

// 搜索关键字
const filterText = ref('')
watch(filterText, val => {
  !treeRef.value.filter(val)
})
// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return (
    data[treeProps.value.label ? treeProps.value.label : 'label'].indexOf(
      value
    ) !== -1
  )
}

/**
 * 取消节点
 * @returns {Promise<void>}
 */
const delNode = node => {
  console.info('node', node)
  if (treeOption.value.defaultCheckedKeys != '') {
    if (treeOption.value.defaultCheckedKeys.indexOf(node.itemValue) != -1) {
      treeOption.value.defaultCheckedKeys.splice(
        treeOption.value.defaultCheckedKeys.indexOf(node.itemValue),
        1
      )
      treeRef.value.setCheckedKeys(treeOption.value.defaultCheckedKeys, true)
    }
  }

  proxy.$nextTick(() => {
    treeRef.value.setChecked(node, false, true)
  })
}

/**
 * 清空选中数据
 * @returns {Promise<void>}
 */
const emptySelectData = () => {
  treeRef.value.setCheckedKeys([])
}

// 暴露方法给父组件
defineExpose({
  delNode,
  emptySelectData
})

// 获取数据
const getTreeData = async () => {
  switch (treeOption.value.dataType) {
    // 人员
    case 'person':
      let personParam = {
        deptId: ''
      }
      //   判断是否传参
      if (treeOption.value.apiParams) {
        personParam = treeOption.value.apiParams
      }
      // 获取人员数据
      const res = await commonStore.getUseTreeData(personParam)
      treeOption.value.data = res
      let sData = [...treeOption.value.defaultCheckedKeys]
      if (sData[0] != undefined && sData[0].toString().indexOf('U') == -1) {
        let newData = []
        sData.forEach(item => {
          newData.push('U' + item)
        })
        treeOption.value.defaultCheckedKeys = newData
      }
      break
    // 单位
    case 'org':
      let orgParam = {
        deptId: ''
      }
      //   判断是否传参
      if (treeOption.value.apiParams) {
        orgParam = treeOption.value.apiParams
      }
      // 获取公司数据
      let data = { deptType: 1 }

      const orgRes = await getListWithRole(data)
      orgRes.data.forEach(item => {
        item.disabled = item.deptId === 100 ? true : false
      })
      treeOption.value.data = handleTree(orgRes.data, 'deptId')

      break
    // 部门
    case 'dept':
      let deptParam = {
        deptId: ''
      }
      //   判断是否传参
      if (treeOption.value.apiParams) {
        deptParam = treeOption.value.apiParams
      }
      const deptRes = await getListWithRole(deptParam)
      deptRes.data.forEach(item => {
        item.disabled = item.deptType === '1' ? true : false
      })
      treeOption.value.data = handleTree(deptRes.data, 'deptId')
      break
    // 岗位
    case 'post':
      const postRes = await commonStore.getPostData()
      treeOption.value.data = postRes
      break
    // 职务
    case 'duties':
      treeOption.value.data = rsgl_ygda_position
      break
  }
  treeOption.value.defaultExpandedKeys = treeOption.value.data
    ? [treeOption.value.data[0][treeOption.value.nodeKey]]
    : []

  if (treeOption.value.defaultCheckedKeys != undefined) {
    proxy.$nextTick(() => {
      let sData = treeRef.value.getCheckedNodes() //获取选中的值
      selectData.value = treeOption.value.checkStrictly
        ? sData
        : sData.filter(item => !item.children)
    })
  }
}

// tree点击选中
const nodeClick = (data, checked) => {
  console.log(data, checked, '查看点击选中')
  if (!treeOption.value.multiple) {
    if (checked) {
      treeOption.value.defaultCheckedKeys = [data[treeOption.value.nodeKey]]
      treeRef.value.setCheckedKeys([data[treeOption.value.nodeKey]])
    } else {
      if (
        treeOption.value.defaultCheckedKeys &&
        treeOption.value.defaultCheckedKeys[0] ===
          data[treeOption.value.nodeKey]
      ) {
        treeRef.value.setCheckedKeys([data[treeOption.value.nodeKey]])
      }
    }
  }
  let nodes = treeRef.value.getCheckedNodes() //获取选中的值

  const sData = treeOption.value.checkStrictly
    ? nodes
    : nodes.filter(item => !item.children)
  const result = sData.map(item => {
    item.itemLabel =
      item[
        treeOption.value.treeLabelName
          ? treeOption.value.treeLabelName
          : 'label'
      ]
    item.itemValue =
      treeOption.value.dataType == 'person'
        ? item[treeOption.value.nodeKey].replace('U', '') * 1
        : item[treeOption.value.nodeKey]

    return item
  })
  treeOption.value.selectData = result
  emit('ok', treeOption.value)
}
</script>

<style scoped lang="scss">
.customNodeClass {
  :deep(.el-checkbox__inner) {
    @apply rounded-50;
  }
}
:deep(.el-tree .is-disabled) {
  display: none;
}
</style>
